"""

A small Test application to show how to use Flask-Raspberry.

"""
from flask import Flask, render_template,request
from flask_mqtt import Mqtt
from flask_serial import Serial
from flask_socketio import SocketIO
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy


import eventlet
eventlet.monkey_patch()

import json
import config

app = Flask(__name__)
app.config.from_object(config)

db = SQLAlchemy(app)
mqtt = Mqtt(app)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)
ser = Serial(app)
ser.ser.loop_start()


# mqtt主题订阅
topics = ["17740171896"]
for t in topics:
    mqtt.subscribe(topic=t, qos=0)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/base')
def home():
    return render_template('base.html')

@app.route('/node')
def node():
    return render_template('node.html')

@app.route('/serial')
def serial():
    return render_template('serial.html')

'''
SocketIO Functions
'''
@socketio.on('publish')
def handle_publish(json_str):
    print("推送消息")
    data = json.loads(json_str)
    mqtt.publish(data['topic'], data['message'])

@socketio.on('subscribe')
def handle_subscribe(json_str):
    data = json.loads(json_str)
    print(data)
    mqtt.subscribe(data['topic'])

@socketio.on('send')
def handle_send(json_str):
    data = json.loads(json_str)
    ser.on_send(data['message'])
    print("send to serial: %s"%data['message'])

'''
Mqtt Functions
'''
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    data = dict(
        topic=message.topic,
        payload=message.payload.decode()
    )

@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
    print(level, buf)

'''
Serial Functions
'''
@ser.on_message()
def handle_ser_message(msg):
    print(msg)
    socketio.emit("serial_message", data={"message":str(msg)})

@ser.on_log()
def handle_ser_logging(level, buf):
    print(buf)

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000, debug=False)
